<template>
  <el-sub-menu 
    v-if="hasVisibleChildren"
    :index="resolvedPath"
  >
    <template #title>
      <svg-icon v-if="item.meta.icon" :icon-class="item.meta.icon" />
      <span>{{ item.meta.title }}</span>
    </template>
    <sidebar-item
      v-for="child in visibleChildren"
      :key="child.path"
      :item="child"
      :base-path="resolvedPath"
    />
  </el-sub-menu>

  <el-menu-item 
    v-else 
    :index="resolvedPath"
    @click="handleNavigation"
  >
    <svg-icon v-if="item.meta.icon" :icon-class="item.meta.icon" />
    <template #title>
      {{ item.meta.title }}
    </template>
  </el-menu-item>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { isExternal } from '@/utils/validate'
import { resolveRoutePath } from '@/utils/router'

const router = useRouter()
const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  basePath: {
    type: String,
    default: ''
  }
})

// 计算解析后的路径
const resolvedPath = computed(() => {
  if (isExternal(props.item.path)) {
    return props.item.path
  }
  return resolveRoutePath(props.item.path, props.basePath)
})

// 判断是否有可见子菜单
const hasVisibleChildren = computed(() => {
  return visibleChildren.value.length > 0
})

// 过滤可见的子路由
const visibleChildren = computed(() => {
  return (props.item.children || []).filter(child => 
    !child.meta?.hidden && (child.component || child.children?.length)
  )
})

// 处理导航逻辑
const handleNavigation = () => {
  if (isExternal(props.item.path)) {
    window.open(props.item.path)
  } else {
    router.push(resolvedPath.value).catch(err => {
      if (!err.name.includes('NavigationFailure')) {
        console.error('导航失败:', err)
      }
    })
  }
}
</script>